<?php
/**
 * User: 1971229701@qq.com
 * Date: 2020/11/2/002
 * Time: 10:39
 */

namespace app\admin\logic;


use app\common\logic\BaseLogic;
use app\common\model\Admin;
use app\common\validate\AdminVal;

class AdminLogic extends BaseLogic
{

    public function listing($keyword, $page_size = 10)
    {
        $where = [];
        !empty($keyword) && $where['username'] = ['like', "%$keyword%"];

        $r = Admin::where($where)->paginate($page_size)->toArray();
        return $r;
    }

    public function create($data)
    {
        $validate = new AdminVal();
        if (!$validate->scene('create')->check($data)) {
            $this->error = $validate->getError();
            return false;
        }

        (new Admin())->save($data);
        return true;
    }

    public function update($data, $methods = 'post')
    {
        if ($methods === 'get') {
            $r = Admin::get($data);
        } else {
            $validate = new AdminVal();
            if (!$validate->scene('create')->check($data)) {
                $this->error = $validate->getError();
                return false;
            }

            $query = Admin::get($data['id']);
            if ($query['password'] != $data['password'] && !empty($data['password'])) {
                $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
            }

            $r = (new Admin())->update($data);
        }
        return $r;
    }

    public function delete($ids)
    {
        $str = trim($ids,',');
        $_arr = explode(',',$str);
        $where[] = ['id','in',$_arr];
        $r = Admin::where($where)->delete();
        return $r;
    }
}